import http from './HTTP'
import api from './api'

let parsePol = [] //格式转化,string=>[{string:num}]
let length = 0 //景点数量
let title = '' //标题
let titleArr = [] //标题们
//设置data
let params = {
  key: 'NMKBZ-SACK6-WFDSR-M7UUJ-Q7OYF-FQB6V',
  table_id: '60530e43edbe45292209e9f2',
  page_index: 1,
  page_size: 200,
}
// get请求获取地点数据
http.get(api.url, params, res => {
  console.log('getTitle.js,请求成功');
  // console.log(res.data.result.data);
  for (let i = 0; i < res.data.result.data.length; i++) {
    //多边形坐标数据格式转化,string=>[{string:num}]
    parsePol.push(res.data.result.data[i].polygon.split(';')
      .map(str => str.split(','))
      .map(([latitude, longitude]) => ({
        latitude,
        longitude,
      })))
    titleArr.push(res.data.result.data[i].title)
    length = res.data.result.data.length
  }

}, err => {
  console.log('错误信息,', err);
})

//判断点是否在范围内
let IsPtInPoly = (aLat, aLon, pointList) => {
  var iSum = 0
  var iCount = pointList.length
  if (iCount < 3) {
    return false
  }
  for (var i = 0; i < iCount; i++) {
    var pLat1 = pointList[i].latitude
    var pLon1 = pointList[i].longitude
    if (i == iCount - 1) {
      var pLat2 = pointList[0].latitude
      var pLon2 = pointList[0].longitude
    } else {
      var pLat2 = pointList[i + 1].latitude
      var pLon2 = pointList[i + 1].longitude
    }
    if (((aLat >= pLat1) && (aLat < pLat2)) || ((aLat >= pLat2) && (aLat < pLat1))) {
      if (Math.abs(pLat1 - pLat2) > 0) {
        var pLon = pLon1 - ((pLon1 - pLon2) * (pLat1 - aLat)) / (pLat1 - pLat2);
        if (pLon < aLon) {
          iSum += 1
        }
      }
    }
  }
  if (iSum % 2 != 0) {
    return true
  } else {
    return false
  }
}
//判断是否在范围内，并且播报
//弹窗播报的内容
let getTitle = (lat, lng) => {
  let result
  for (let i = 0; i < length; i++) {
    result = IsPtInPoly(lat, lng, parsePol[i])
    if (result) {
      title = titleArr[i]
    }
  }
  console.log(result);
  return title
}
export default {
  getTitle
}